package com.tfxy.hxl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tfxy.hxl.entity.CourseCategory;
import com.tfxy.hxl.mapper.CourseCategoryMapper;
import com.tfxy.hxl.service.CourseCategoryService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * 课程分类服务实现类
 */
@Service
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements CourseCategoryService {

    @Override
    public List<CourseCategory> getEnabledCategories() {
        QueryWrapper<CourseCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1)
                   .eq("deleted", 0)
                   .orderByAsc("sort_order");
        return list(queryWrapper);
    }

    @Override
    public CourseCategory getCategoryByName(String name) {
        if (!StringUtils.hasText(name)) {
            return null;
        }
        QueryWrapper<CourseCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name)
                   .eq("deleted", 0);
        return getOne(queryWrapper);
    }

    @Override
    public boolean createCategory(CourseCategory category) {
        if (category == null || !StringUtils.hasText(category.getName())) {
            return false;
        }
        
        // 检查名称是否已存在
        if (getCategoryByName(category.getName()) != null) {
            return false;
        }
        
        category.setCreateTime(new Date());
        category.setUpdateTime(new Date());
        category.setDeleted(0);
        if (category.getStatus() == null) {
            category.setStatus(1);
        }
        
        return save(category);
    }

    @Override
    public boolean updateCategory(CourseCategory category) {
        if (category == null || category.getId() == null) {
            return false;
        }
        
        // 如果更新名称，检查是否与其他分类重名
        if (StringUtils.hasText(category.getName())) {
            CourseCategory existing = getCategoryByName(category.getName());
            if (existing != null && !existing.getId().equals(category.getId())) {
                return false;
            }
        }
        
        category.setUpdateTime(new Date());
        return updateById(category);
    }

    @Override
    public boolean deleteCategory(Long categoryId) {
        if (categoryId == null) {
            return false;
        }
        
        UpdateWrapper<CourseCategory> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", categoryId)
                    .set("deleted", 1)
                    .set("update_time", new Date());
        
        return update(updateWrapper);
    }
}
